<template>
  <el-card shadow="never" class="rd-8 mb-8">
    <el-form :model="queryParams" class="flex">
      <el-form-item label="用户名" class="form-item">
        <el-input
          placeholder="请输入用户名"
          class="w-250"
          v-model="queryParams.username"
          clearable
        />
      </el-form-item>
      <el-form-item label="手机号" class="form-item">
        <el-input
          placeholder="请输入手机号"
          class="w-250"
          clearable
          v-model="queryParams.mobile"
        />
      </el-form-item>
      <el-form-item label="状态" class="form-item">
        <el-select
          v-model="queryParams.isDisabled"
          class="w-250"
          clearable
          placeholder="用户状态"
        >
          <el-option label="正常" :value="false" />
          <el-option label="禁用" :value="true" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" class="form-item">
        <el-date-picker
          v-model="rangeDate"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          clearable
          class="w-250"
        />
      </el-form-item>
      <el-form-item class="form-item">
        <el-button type="primary" icon="Search" @click="getHasUser()" />
        <el-button type="primary" icon="RefreshLeft" @click="queryReset()" />
      </el-form-item>
    </el-form>
    <el-button
      @click="openUpdateAndAddDialog()"
      icon="Plus"
      type="primary"
      plain
    >
      添加用户
    </el-button>
    <el-button
      icon="Delete"
      type="danger"
      plain
      :disabled="selectedIds.length == 0"
      @click="removeUser()"
    >
      批量删除
    </el-button>
  </el-card>

  <el-card shadow="never" class="rd-8">
    <el-table
      :data="userArr"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="selection"
      />
      <el-table-column label="序号" width="55" type="index" align="center">
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        align="center"
        width="180"
      />
      <el-table-column
        prop="mobile"
        label="手机号"
        align="center"
        width="180"
      />
      <el-table-column prop="sex" label="性别" align="center" width="180">
        <template #default="{ row }">
          <el-tag v-if="row.sex === 0">男</el-tag>
          <el-tag type="danger" v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="头像" align="center" width="180">
        <template #default="{ row }">
          <div class="f-c-c">
            <img
              :src="
                row.avatar ||
                'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
              "
              class="w-100 h-100 rounded-full"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sign" label="用户签名" align="center" width="180">
        <template #default="{ row }">
          <el-popover
            effect="light"
            trigger="hover"
            placement="top"
            width="auto"
          >
            <template #default>
              <div class="w-150 mb-2">
                {{ row.sign }}
              </div>
            </template>
            <template #reference>
              <el-text class="w-150 mb-2" truncated>
                {{ row.sign }}
              </el-text>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="180"
      />
      <el-table-column prop="isDisabled" label="禁用" align="center" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.isDisabled"
            inline-prompt
            active-text="是"
            inactive-text="否"
            @change="(val) => handleSwitchChange(row.userId, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="openUpdateAndAddDialog(row)"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="removeUser(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pt-10">
      <el-pagination
        @size-change="sizeChange"
        @current-change="getHasUser"
        :pager-count="9"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </div>
  </el-card>

  <el-dialog
    v-model="dialogFormVisible"
    :title="userForm.userId ? '修改用户' : '添加用户'"
  >
    <el-form style="width: 80%" :model="userForm" ref="formRef" :rules="rules">
      <el-form-item label="用户名" label-width="100px" prop="username">
        <el-input
          placeholder="请输入用户名"
          v-model="userForm.username"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="密码"
        label-width="100px"
        prop="password"
        v-if="userForm.userId"
      >
        <el-input
          placeholder="请输入密码"
          show-password
          v-model="userForm.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="100px" prop="mobile">
        <el-input
          placeholder="请输入手机号"
          v-model="userForm.mobile"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别" label-width="100px" prop="sex">
        <el-radio-group v-model="userForm.sex" class="ml-4">
          <el-radio border :label="0">男</el-radio>
          <el-radio border :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄" label-width="100px" prop="age">
        <el-input-number v-model="userForm.age" :min="0" :max="100" />
      </el-form-item>
      <el-form-item label="头像" label-width="100px" prop="avatar">
        <CropperImage v-model="userForm.avatar" />
      </el-form-item>
      <el-form-item label="禁用" label-width="100px" prop="isDisabled">
        <el-switch
          v-model="userForm.isDisabled"
          inline-prompt
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>
      <el-form-item label="签名" label-width="100px" prop="sign">
        <el-input
          placeholder="请输入签名"
          v-model="userForm.sign"
          autosize
          type="textarea"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" plain size="default" @click="cancel()">
        取消
      </el-button>
      <el-button type="primary" size="default" @click="confirm()">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  reqChangeUserStatus,
  reqDeleteUser,
  reqUpdateAndAddUser,
  reqUserPage,
} from '@/api/user'
import CropperImage from '@/components/CropperImage/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, onMounted, ref } from 'vue'

let userArr = ref([])
let pageNum = ref(1)
let pageSize = ref(5)
let total = ref(0)
let selectedIds = ref([])
let queryParams = ref({})
let rangeDate = ref([])
// 禁用切换
const handleSwitchChange = async (userId, val) => {
  try {
    await reqChangeUserStatus(userId, val)
  } catch (error) {
    userArr.value.find((item) => item.userId === userId).isDisabled = !val
  }
}

// 清空查询
const queryReset = () => {
  queryParams.value = {}
  rangeDate.value = []
  getHasUser()
}

const openUpdateAndAddDialog = (row = {}) => {
  dialogFormVisible.value = true
  userForm.value = row
  nextTick(() => {
    const keysArray = Object.keys(rules)
    formRef.value.clearValidate(keysArray)
  })
}
/* 分页切换 */
const getHasUser = async (pager = 1) => {
  pageNum.value = pager
  if (rangeDate.value && rangeDate.value.length == 2) {
    queryParams.value.startTime = rangeDate.value[0]
    queryParams.value.endTime = rangeDate.value[1]
  } else {
    queryParams.value.startTime = undefined
    queryParams.value.endTime = undefined
  }
  const result = await reqUserPage(
    pageNum.value,
    pageSize.value,
    queryParams.value,
  )
  userArr.value = result.rows
  // console.log(result.rows)
  total.value = result.total
}
/* 分页大小改变 */
const sizeChange = () => {
  getHasUser()
}
/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map((item) => item.uid)
}
const removeUser = (row) => {
  const userIds = row ? row.uid : selectedIds.value
  ElMessageBox.confirm(
    `是否确认删除用户编号为【${userIds}】的数据项？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await reqDeleteUser(userIds)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      await getHasUser(pageNum.value || 1)
    })
    .catch(() => {})
}
onMounted(() => {
  getHasUser()
})

// dialog
let dialogFormVisible = ref(false)
let formRef = ref()
let userForm = ref({})

//表单校验规则对象
const rules = {
  username: [
    {
      required: true,
      min: 3,
      max: 10,
      message: '账号长度至少三位',
      trigger: 'blur',
    },
  ],
  age: [
    {
      required: true,
      min: 0,
      max: 100,
      type: 'number',
      message: '年龄应该在0-100之间',
      trigger: 'blur',
    },
  ],
  sex: [
    {
      required: true,
      message: '选择性别',
      trigger: 'blur',
    },
  ],
}

const cancel = () => {
  dialogFormVisible.value = false
}
const confirm = async () => {
  try {
    // 表单校验
    await formRef.value.validate()
    dialogFormVisible.value = false
    const result = await reqUpdateAndAddUser(userForm.value)
    ElMessage.success(userForm.value.userId ? '修改用户成功' : '添加用户成功')

    await getHasUser(userForm.value.userId ? pageNum.value : 1)
  } catch (error) {}
}
</script>

<style lang="scss" scoped>
.form-item {
  margin: 0 10px 18px 0;
}
</style>
